const router = require('koa-router')()
const moment = require('moment')
const { Fb } = require('../class/utils')
const Order = require('../class/order')
const Attractions = require('../class/attractions')

router.prefix('/')

// 添加订单
router.post('/createOrder.do', async ctx => {
  const form = ctx.request.body
  let librData = await Fb.callback(Attractions.celectLibrary(form.pid))
  try{
      if((parseInt(librData.data.num) - parseInt(form.num)) < 0){
        ctx.body = Fb.error('购买失败,库存不足!')
        return false
      }
  }catch(e){
    ctx.body = Fb.error('购买失败!')
  }
  let orderData = await Fb.callback(Order.create(form))
  if (orderData.status) {
    let librData = await Fb.callback(Attractions.downLibrary(form))
    if(librData.status){
        ctx.body = Fb.success(orderData);
    }else{
        Order.delete(orderData.data.id)
        ctx.body = Fb.error('购买失败!')
    }
  }else{
    ctx.body = Fb.error('购买失败!')
  }
})

// 获取订单列表
router.post('/getOrderList.do', async ctx => {
  const form = ctx.request.body
  let nowPage = parseInt(form.nowPage) || 1
  let pageSize = parseInt(form.pageSize) || 9999999
  if(form.type == 1){
    ctx.body = await Fb.callback(Order.select(form, nowPage, pageSize))
  }else{
    ctx.body = await Fb.callback(Order.selectOne(form, nowPage, pageSize))
  }
})

//订单退票
router.post('/updateOrder.do', async ctx => {
    const form = ctx.request.body
    let orderData = await Fb.callback(Order.update(form))
    if(orderData.status){
        Attractions.addLibrary(form)
        ctx.body = Fb.success(orderData)
    }else{
        ctx.body = Fb.error('退款失败')
    }
  })
  

// 删除订单
router.post('/deleteOrder.do', async ctx => {
  const form = ctx.request.body
  ctx.body = await Fb.callback(Order.delete(form))
})

module.exports = router
